/*
 * @Date         : 2024-05-11 17:15:40 星期6
 * @Author       : xut
 * @Description  :
 */
import grpc from "@grpc/grpc-js"
import protoLoader from "@grpc/proto-loader"
import { resolve, dirname } from "node:path"
import { fileURLToPath } from "node:url"

const __dirname = dirname(fileURLToPath(import.meta.url))

const PROTO_PATH = resolve(__dirname, "./helloworld.proto")

const packageDefinition = protoLoader.loadSync(PROTO_PATH, {
  keepCase: true,
  longs: String,
  enums: String,
  defaults: true,
  oneofs: true,
})

const protoDescriptor = grpc.loadPackageDefinition(packageDefinition)
const helloProto = protoDescriptor.helloworld // helloworld 为 proto 中 package 字段定义的包名

const GreeterServiceImpl = {
  sayHello: (call, cb) => {
    const response = { message: "Hello " + call.request.name }
    cb(null, response)
  },
}

function main() {
  // 创建一个服务对象
  const server = new grpc.Server()
  // 添加 proto 中的服务，以及对应的实现。如果多个服务，多次调用
  server.addService(helloProto.Greeter.service, GreeterServiceImpl)
  // 服务绑定地址和端口
  server.bindAsync(
    "localhost:50051",
    grpc.ServerCredentials.createInsecure(),
    (err, port) => {
      if (err !== null) {
        return console.error(err)
      }

      console.log("gRPC listening on localhost:" + port)
    }
  )
}
main()
